import datetime
import hashlib
import hmac
import json
import os
import subprocess

import requests
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
    TencentCloudSDKException,
)
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.cvm.v20170312 import cvm_client, models
from tencentcloud.tmt.v20180321 import models, tmt_client


class PromptOptimizeMachine:
    """提示词优化器"""

    def __init__(self, prompt, negative_prompt):
        self.prompt = prompt
        self.negative_prompt = negative_prompt

    def optimize(self, mode: str) -> tuple:
        """优化提示词"""
        # 校验提示词有效性
        if not self.prompt and not self.negative_prompt:
            if self.prompt == self.negative_prompt:
                return None

        if mode != "None":
            self.prompt = self.translate_text(self.prompt)
            self.negative_prompt = self.translate_text(self.negative_prompt)

        # 提示词嵌入模板
        # https://github.com/Dalabad/stable-diffusion-prompt-templates
        if mode == "建筑":
            template = """{{Prompt}}, shot 35 mm, realism, octane render, 8k, trending on artstation, 35 mm camera, unreal engine, hyper detailed, photo - realistic maximum detail, volumetric light, realistic matte painting, hyper photorealistic, trending on artstation, ultra - detailed, realistic"""
            self.prompt = template.replace("{{Prompt}}", self.prompt)

        elif mode == "肖像":
            template = """portrait photo of {{Prompt}}, photograph, highly detailed face, \
depth of field, moody light, golden hour, style by Dan Winters, Russell James, \
Steve McCurry, centered, extremely detailed, Nikon D850, award winning photography"""
            self.prompt = template.replace("{{Prompt}}", self.prompt)

        elif mode == "卡通":
            template = """{{Prompt}}, anthro, very cute kid's film character, disney pixar zootopia \
character concept artwork, 3d concept, detailed fur, high detail iconic character \
for upcoming film, trending on artstation, character design, 3d artistic render, \
highly detailed, octane, blender, cartoon, shadows, lighting"""
            self.prompt = template.replace("{{Prompt}}", self.prompt)

        elif mode == "游戏":
            template = """sprite of video games {{Prompt}} icons, 2d icons, rpg skills icons, world of warcraft, league of legends, ability icon, fantasy, potions, spells, objects, flowers, gems, swords, axe, hammer, fire, ice, arcane, shiny object, graphic design, high contrast, artstation"""
            self.prompt = template.replace("{{Prompt}}", self.prompt)

        return self.prompt, self.negative_prompt

    def translate_text(self, text):
        """prompt 翻译"""
        secret_id = os.getenv("TENCENTCLOUD_SECRET_ID")
        secret_key = os.getenv("TENCENTCLOUD_SECRET_KEY")

        # 校验密钥有效性
        if not secret_id or not secret_key:
            return None

        cred = credential.Credential(secret_id, secret_key)

        try:
            httpProfile = HttpProfile()
            httpProfile.endpoint = "tmt.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = tmt_client.TmtClient(cred, "ap-beijing", clientProfile)

            req = models.TextTranslateRequest()
            req.SourceText = text
            req.Source = "zh"
            req.Target = "en"
            req.ProjectId = 0

            resp = client.TextTranslate(req)
            return json.loads(resp.to_json_string())["TargetText"]

        except TencentCloudSDKException as err:
            print(err)

    @staticmethod
    def is_all_chinese(strs):
        for _char in strs:
            if not "\u4e00" <= _char <= "\u9fa5":
                return False
        return True


def load_config(file_path):
    config = {}
    with open(file_path, "r") as file:
        for line in file:
            name, value = line.strip().split("=")
            config[name] = value
    return config


if __name__ == "__main__":
    config = load_config("config.conf")
    os.environ["TENCENTCLOUD_SECRET_ID"] = config.get("SecretId")
    os.environ["TENCENTCLOUD_SECRET_KEY"] = config.get("SecretKey")
    pom = PromptOptimizeMachine("A person", "Not a car")
    print(pom.translate_text("一个大大的心心"))
    print(pom.translate_text("school"))
